import { useState } from "react"
import { keepPreviousData, useQuery } from "@tanstack/react-query"
import { Button, Checkbox, Col, message, Row, Tag, Tooltip, Pagination } from "antd"
import { FormOutlined, DeleteOutlined, DeploymentUnitOutlined, PlusOutlined } from "@ant-design/icons"
import SearchForm from "@/components/searchForm"
import ItemIcon from "@/assets/images/layout/u1286.png"
import useStyles from "./styles"
import { ModalForm, ProFormItem, ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-components"
import { serviceFlowAdd, getFlowDefinitionPage, updateFlowDefinition, serviceFlowDelete } from "@/api/sharing/serviceFlow"
import { useDictOptions } from "@/hooks"
import { Link } from "react-router-dom"
import ParamSetting from "./design/components/form/ParamSetting"

import { flowDefineService } from '@/flowService';

const queryItems = [
  {
    name: 'keyword',
    label: '负载名称',
    type: 'INPUT',
  },
  {
    name: 'flowType',
    label: '工作流类型',
    type: 'SELECT',
    options: [
      {
        label: '数据清洗',
        value: '1',
      },
      {
        label: '数据处理',
        value: '2',
      }
    ]
  },
]

const ServiceFlow = () => {
  const { styles } = useStyles()
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [searchParams, setSearchParams] = useState({});
  const [fullData, setFullData] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13])
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const { data: tableData = [], isFetching, refetch } = useQuery({
    queryKey: ['page-ServiceFlow-getFlowDefinitionPage', page, searchParams],
    queryFn: () => {
      return getFlowDefinitionPage({
        pageNo: page.pageNo,
        pageSize: page.pageSize,
        ...searchParams
      }).then(res => {
        return res.data || {}
      })
    },
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const handleAdd = (values) => {
    let api_func = values.id ? updateFlowDefinition : serviceFlowAdd
    return api_func(values).then(res => {
      if (res.code === 200) {
        refetch()
        message.success(values.id ? '编辑成功' : '新增成功')
        return true
      }
    })
  }

  const deleteConfirm = (id) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除选中的工作流吗？',
      onOk: () => {
        serviceFlowDelete(id).then(res => {
          if (res.code === 200) {
            refetch()
            message.success('删除成功')
          }
        })
      }
    })
  }

  return (
    <div className={styles.indexWrapper}>
      <div className="searchTableHeader">服务编排</div>
      <SearchForm
        onSearch={(values) => {
          if (JSON.stringify(values) !== JSON.stringify(searchParams)) {
            setSearchParams({ ...values })
          } else {
            refetch()
          }
        }}
        items={queryItems}
        buttons={<>
          <AddFlowForm title="新增工作流" onFinish={handleAdd} trigger={<Button icon={<PlusOutlined />} type="primary">新建工作流</Button>} />
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
        </>}
      />
      <Row gutter={[15, 15]}>
        {(tableData.list || []).map(item => (
          <Col key={item.id} xs={24} sm={24} md={12} lg={8} xl={6} >
            <div className="flowItem">
              <div className="itemTop">
                <div className="imgWrap"><img src={ItemIcon} alt="" /></div>
                <div className="itemContent">
                  <div className="title">{item.flowName}</div>
                  <div className="attrItem">
                    <span className="attrKey">工作流类型：</span>
                    <Tag>{item.flowType === '1' ? '数据清洗' : '数据处理'}</Tag>
                  </div>
                  <div className="attrItem">
                    <span className="attrKey">创建时间：</span>
                    <span className="attrValue">{item.createdAt}</span>
                  </div>
                  <div className="attrItem">
                    <span className="attrKey">工作流描述：</span>
                    <span className="attrValue" title="ss">{item.remark}</span>
                  </div>
                </div>
              </div>
              <div className="itemBottom">
                <AddFlowForm
                  title="编辑工作流"
                  onFinish={handleAdd}
                  request={() => {
                    return flowDefineService.getDefineInfo(item.id).then(res => {
                      return {
                        ...(res.data || {}),
                        flowInputParams: res.data?.flowInputParams || [],
                        flowOutputParams: res.data?.flowOutputParams || [],
                      }
                    })
                  }}
                  trigger={<Tooltip title="编辑工作流"><Button size="large" type="text" icon={<FormOutlined />}></Button></Tooltip>} />
                <Tooltip title="设计工作流">
                  <Link to={`/integration/sharing/serviceFlow/design/${item.id}`}>
                    <Button size="large" type="text" icon={<DeploymentUnitOutlined />}></Button>
                  </Link>
                </Tooltip>
                <Tooltip title="删除工作流">
                  <Button size="large" type="text" icon={<DeleteOutlined />} onClick={() => deleteConfirm(item.id)}></Button>
                </Tooltip>
              </div>
              <div className="checkboxWrap">
                <Checkbox />
              </div>
            </div>
          </Col>
        ))}
      </Row>
      <Pagination
        align="end"

        total={tableData.total}
        current={page.pageNo}
        pageSize={page.pageSize}
        onChange={(pageNo, pageSize) => {
          setPage({ ...page, pageNo, pageSize })
          refetch()
        }}
      />
    </div>
  )
}


const AddFlowForm = (props) => {
  const { data: typeOptions } = useDictOptions('service_flow_type')
  return (
    <ModalForm
      width={'600px'}

      modalProps={{ destroyOnClose: true }}
      grid={true}
      {...props}
    >
      <ProFormItem name="id" hidden />
      <ProFormText name="flowName" label="工作流名称" placeholder="请输入名称" rules={[{ required: true, message: '名称不能为空' }]} />
      <ProFormSelect name="flowType" label="工作流类型" placeholder="请选择类型" options={typeOptions} rules={[{ required: true, message: '类型不能为空' }]} />
      <ProFormTextArea name="remark" label="工作流说明" />

      <Col span={24}>
        <ProFormItem name="flowInputParams" label="新增入参">
          <ParamSetting addText="新增入参" showRequired />
        </ProFormItem>
      </Col>

      <Col span={24}>
        <ProFormItem name="flowOutputParams" label="新增出参">
          <ParamSetting addText="新增出参" />
        </ProFormItem>
      </Col>
    </ModalForm>
  )
}


export default ServiceFlow
